<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 记录日志
$log = [];
$success = true;

// 记录PHP信息
$log[] = "PHP版本: " . phpversion();
$log[] = "服务器系统: " . PHP_OS;

// 检查配置文件存在
$configFile = __DIR__ . '/../config/database.php';
if (file_exists($configFile)) {
    $log[] = "数据库配置文件存在";
    
    // 尝试引入数据库配置
    try {
        require_once $configFile;
        $log[] = "数据库配置文件成功加载";
        
        // 检查数据库连接
        try {
            $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
            $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $log[] = "数据库连接成功";
        } catch (PDOException $e) {
            $success = false;
            $log[] = "数据库连接失败: " . $e->getMessage();
        }
    } catch (Exception $e) {
        $success = false;
        $log[] = "加载数据库配置文件失败: " . $e->getMessage();
    }
} else {
    $success = false;
    $log[] = "数据库配置文件不存在";
}

// 检查重要文件
$files = [
    'includes/header.php',
    'includes/footer.php',
    'includes/AdminAuth.php',
    'includes/functions.php'
];

foreach ($files as $file) {
    $fullPath = __DIR__ . '/' . $file;
    if (file_exists($fullPath)) {
        $log[] = "文件 {$file} 存在";
        
        // 读取文件内容进行简单分析
        $content = file_get_contents($fullPath);
        $size = strlen($content);
        $log[] = "- 文件大小: {$size} 字节";
        
        // 检查特定关键词
        if (strpos($content, 'database') !== false) {
            $log[] = "- 文件包含数据库相关代码";
        }
        if (strpos($content, 'class AdminAuth') !== false) {
            $log[] = "- 文件包含 AdminAuth 类定义";
        }
        if (strpos($content, 'session_start') !== false) {
            $log[] = "- 文件包含会话启动代码";
        }
    } else {
        $success = false;
        $log[] = "文件 {$file} 不存在";
    }
}

// 检查login.php
$loginFile = __DIR__ . '/login.php';
if (file_exists($loginFile)) {
    $log[] = "login.php 文件存在";
    $content = file_get_contents($loginFile);
    $log[] = "login.php 内容大小: " . strlen($content) . " 字节";
    
    // 分析可能的问题
    if (strpos($content, 'require_once') === false) {
        $log[] = "警告: login.php 没有包含其他文件";
    }
    if (strpos($content, 'header.php') === false) {
        $log[] = "警告: login.php 没有包含 header.php";
    }
    if (strpos($content, 'footer.php') === false) {
        $log[] = "警告: login.php 没有包含 footer.php";
    }
    
    // 尝试修复login.php
    $fixed = false;
    if (!$fixed) {
        // 创建一个修复后的login.php文件
        $newLoginFile = __DIR__ . '/fixed_login.php';
        $newContent = <<<EOT
<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 引入必要文件
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/includes/functions.php';

// 初始化会话
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 创建PDO数据库连接
\$dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
\$pdo = new PDO(\$dsn, DB_USERNAME, DB_PASSWORD);
\$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 处理登录表单提交
\$error = null;
if (\$_SERVER['REQUEST_METHOD'] === 'POST') {
    \$username = \$_POST['username'] ?? '';
    \$password = \$_POST['password'] ?? '';
    
    if (empty(\$username) || empty(\$password)) {
        \$error = '请输入用户名和密码';
    } else {
        // 查询管理员
        \$stmt = \$pdo->prepare("SELECT * FROM " . DB_PREFIX . "users WHERE (username = ? OR email = ?) AND role = 'admin'");
        \$stmt->execute([\$username, \$username]);
        \$user = \$stmt->fetch(PDO::FETCH_ASSOC);
        
        // 验证密码
        if (\$user && password_verify(\$password, \$user['password'])) {
            // 登录成功，设置会话
            \$_SESSION['admin_user_id'] = \$user['id'];
            \$_SESSION['admin_username'] = \$user['username'];
            
            // 更新最后登录时间
            \$updateStmt = \$pdo->prepare("UPDATE " . DB_PREFIX . "users SET last_login = NOW() WHERE id = ?");
            \$updateStmt->execute([\$user['id']]);
            
            // 设置闪存消息
            \$_SESSION['flash_message'] = '登录成功！';
            \$_SESSION['flash_type'] = 'success';
            
            // 重定向到控制台
            header('Location: index.php');
            exit;
        } else {
            \$error = '用户名或密码错误';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KidsMind管理后台 - 登录</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/admin.css">
</head>
<body class="bg-light">
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-lg-5 col-md-7">
                <div class="card shadow-lg border-0 rounded-lg mt-5">
                    <div class="card-header bg-primary text-white">
                        <h3 class="text-center font-weight-light my-4">KidsMind管理后台登录</h3>
                    </div>
                    <div class="card-body">
                        <?php if (\$error): ?>
                        <div class="alert alert-danger"><?php echo \$error; ?></div>
                        <?php endif; ?>
                        
                        <form method="post">
                            <div class="mb-3">
                                <label for="username" class="form-label">用户名/邮箱</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="bi bi-person"></i></span>
                                    <input type="text" class="form-control" id="username" name="username" required autofocus>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">密码</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="bi bi-key"></i></span>
                                    <input type="password" class="form-control" id="password" name="password" required>
                                </div>
                            </div>
                            
                            <div class="form-check mb-3">
                                <input class="form-check-input" id="remember" name="remember" type="checkbox" value="1">
                                <label class="form-check-label" for="remember">记住我</label>
                            </div>
                            
                            <div class="d-flex align-items-center justify-content-center mt-4 mb-0">
                                <button type="submit" class="btn btn-primary px-4">登录</button>
                            </div>
                        </form>
                    </div>
                    <div class="card-footer text-center py-3">
                        <div class="small"><a href="../index.html">返回前台首页</a></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
EOT;
        file_put_contents($newLoginFile, $newContent);
        $log[] = "已创建修复版本的登录页面: fixed_login.php";
        $fixed = true;
    }
} else {
    $success = false;
    $log[] = "login.php 文件不存在";
}

// 输出详细日志
$fullLog = implode("\n", $log);
$logFile = __DIR__ . '/../logs/login_debug.log';
file_put_contents($logFile, date('Y-m-d H:i:s') . " - Login Debug Log\n" . $fullLog . "\n\n", FILE_APPEND);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KidsMind - 登录页面调试</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header bg-info text-white">
                        <h4 class="mb-0">KidsMind 登录页面调试工具</h4>
                    </div>
                    <div class="card-body">
                        <h5 class="card-title mb-4">调试结果</h5>
                        
                        <div class="alert <?php echo $success ? 'alert-success' : 'alert-danger'; ?>">
                            <?php echo $success ? '基本检查通过' : '存在一些问题需要修复'; ?>
                        </div>
                        
                        <div class="mb-4">
                            <h6>调试日志:</h6>
                            <div class="border p-3 bg-light">
                                <pre><?php echo htmlspecialchars($fullLog); ?></pre>
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <p><strong>解决方案:</strong></p>
                            <ol>
                                <li>我已创建了一个新的登录页面 <a href="fixed_login.php">fixed_login.php</a>，请尝试使用此页面登录</li>
                                <li>如果新的登录页面可以工作，请将其内容复制到login.php替换原来的内容</li>
                                <li>登录成功后，请访问 <a href="add_test_data.php">add_test_data.php</a> 添加测试数据</li>
                            </ol>
                        </div>
                        
                        <div class="mt-4">
                            <a href="fixed_login.php" class="btn btn-primary">使用修复版登录页</a>
                            <a href="test_login.php" class="btn btn-secondary">登录系统诊断</a>
                            <a href="index.php" class="btn btn-warning">尝试直接访问后台</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 